package com.project.zsxd.server.common.helper;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.project.zsxd.server.common.util.HttpUtil;
import com.project.zsxd.server.common.util.JsonUtil;
import com.project.zsxd.server.common.util.LogUtil;
import com.project.zsxd.server.user.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 第三方登录辅助类
 *
 * @author liugh
 * @version 2018年7月25日 下午3:44:45
 */
@Component
public final class ThirdPartyLoginHelper {

    private static Logger logger = LoggerFactory.getLogger(ThirdPartyLoginHelper.class);

    @Value("${app.weixin.appId}")
    private String appId;

    @Value("${app.weixin.appKey}")
    private String appKey;

    @Value("${app.weixin.accessTokenUrl}")
    private String accessTokenUrl;


    /**
     * 设置微信新用户的信息
     * @param userInfoObj
     * @return
     */
    public static final User getWxUserinfo(JSONObject userInfoObj) {
        User newUser = new User();
        newUser.setUserName(userInfoObj.getString("openId"));
        newUser.setOpenId(userInfoObj.getString("openId"));
        newUser.setNickName(userInfoObj.getString("nickName"));
        newUser.setHeadIcon(userInfoObj.getString("avatarUrl"));
        newUser.setCountry(userInfoObj.getString("country"));
        newUser.setProvince(userInfoObj.getString("province"));
        newUser.setCity(userInfoObj.getString("city"));
        if (userInfoObj.getInteger("gender") != null) {
            newUser.setGender(userInfoObj.getIntValue("gender") == 1);
        }
        newUser.setPasswd("45462233");
        newUser.setUseLanguage(userInfoObj.getString("language"));
        newUser.setCreatedBy(newUser.getUserName());
        newUser.setUpdatedBy(newUser.getUserName());
        newUser.setSource("WX");
        newUser.setLastLoginTime(new Date());
        return newUser;
    }

    /**
     * 更新用户信息
     * @param queryUser
     * @param userInfoObj
     * @return
     */
    public static User updateWxUserinfo(User queryUser, JSONObject userInfoObj) {
        queryUser.setNickName(userInfoObj.getString("nickName"));
        queryUser.setHeadIcon(userInfoObj.getString("avatarUrl"));
        queryUser.setCountry(userInfoObj.getString("country"));
        queryUser.setProvince(userInfoObj.getString("province"));
        queryUser.setCity(userInfoObj.getString("city"));
        if (userInfoObj.getInteger("gender") != null) {
            queryUser.setGender(userInfoObj.getIntValue("gender") == 1);
        }
        queryUser.setUseLanguage(userInfoObj.getString("language"));
        queryUser.setUpdatedBy(queryUser.getUserName());
        queryUser.setLastLoginTime(new Date());
        return queryUser;
    }

    /**
     * 获取微信的认证token和用户OpenID
     *
     * @param code
     * @param host
     * @return
     */
    public final Map<String, String> getWxTokenAndOpenid(String code, String host) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        // 获取令牌
        String tokenUrl = accessTokenUrl;
        tokenUrl = tokenUrl + "?appid=" + appId + "&secret="
                + appKey + "&js_code=" + code + "&grant_type=authorization_code";
        String tokenRes = HttpUtil.get(tokenUrl);
        JsonObject tokenObj = JsonUtil.parse2JsonObject(tokenRes);
        LogUtil.info("getWxTokenAndOpenid:{}", tokenRes);
        if (tokenObj != null && tokenObj.has("openid")) {
            map.put("accessToken", tokenObj.get("session_key").getAsString());
            // 获取微信用户的唯一标识openid
            map.put("openId", tokenObj.get("openid").getAsString());
        } else {
            LogUtil.error("getWXToken error.result:{}", tokenRes);
            throw new IllegalArgumentException("获取会话失败");
        }
        return map;
    }

}
